package com.wdf.rule.dynamic;

import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;

/**
 * @author moon
 * @date 2023-02-15 20:00
 * @since 1.8
 */
public class CustomJavaFileManager extends ForwardingJavaFileManager<JavaFileManager> {

    /**
     * 自定义类加载器
     */
    private CustomClassLoader loader;

    /**
     * 初始化
     * @param fileManager
     * @param loader
     */
    protected CustomJavaFileManager(JavaFileManager fileManager, CustomClassLoader loader) {
        super(fileManager);
        this.loader = loader;
    }

    @Override
    public JavaFileObject getJavaFileForOutput(
            JavaFileManager.Location location, String className,
            JavaFileObject.Kind kind, FileObject sibling) {

        try {
            CustomJavaFileObject innerClass = new CustomJavaFileObject(className);
            loader.addJavaCode(innerClass);
            return innerClass;
        } catch (Exception e) {
            throw new RuntimeException("exception when creating in-memory output stream for  " + className, e);
        }
    }

    @Override
    public ClassLoader getClassLoader(JavaFileManager.Location location) {
        return loader;
    }

}
